package com.sduept.nwld.dataserver.controller.equipment.assessment;

import com.sduept.bigdata.equipment.assessment.dto.hiddendangertrack.HiddenDangerTrackDTO;
import com.sduept.bigdata.equipment.assessment.model.hiddendanger.track.HiddenDangerTrack;
import com.sduept.bigdata.equipment.assessment.model.hiddendanger.track.HiddenDangerTrackQueryParamModel;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionExpert;
import com.sduept.bigdata.equipment.assessment.service.*;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.core.entity.AbstractStandardDict;
import com.sduept.core.service.StandardDictService;
import com.sduept.core.service.impl.StandardDictConfigurator;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.utils.PingYinUtil;
import org.primefaces.PrimeFaces;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.NodeUnselectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.*;
import java.util.Map.Entry;

/**
 * 隐患追踪controller类
 */
@Named
@ViewScoped
public class HiddenDangerTrackController extends AbstractController {
	private static final long serialVersionUID = 5233283549395529450L;
	
	@Autowired
    private HiddenDangerTrackService trackService;
	@Autowired
    private InspectionExpertService expertService;
	@Autowired
    private StandardDictService dictService;
	@Autowired
	private InspectionPlanService planService;
	@Autowired
	private StandardDictService sman;
	@Autowired
	private StandardDictConfigurator sdc;
	@Autowired
	private InspectionItemService itemService;
	@Autowired
	private InspectionStationService stationService;
	
   private List<String> voltageList = new ArrayList<String>(); // 电压等级
   private List<String> classList = new ArrayList<String>(); // 对应分类
   private boolean status;//编辑时显示可编辑内容，详细时不可编辑
   private String changeStatus = "true";
   private List<HiddenDangerTrack> tracks;//table显示
   private HiddenDangerTrack selected = null; //表格选择条目
   private TreeNode selectedNode;//节点选择
   private TreeNode trackRoot;//追踪节点
   private HiddenDangerTrackQueryParamModel queryParam = new HiddenDangerTrackQueryParamModel();//查询条件
   private Map<String, List<String>> discMap = null;//字典map
   private Class<? extends AbstractStandardDict> T = null;	
	@PostConstruct
	public void init()  {
		initTracks();
		initDics();
		initTreeTable(tracks);
		initAutoCompleteList();
		
	}
	
	private void initTracks() {
		tracks = trackService.findAll();
	}
	
	/**
	 * 根据track集合构造层级map
	 * @param tracks
	 */
	private Map<String,Map<String,List<HiddenDangerTrack>>> getTrackMap(List<HiddenDangerTrack> tracks) {
		 Map<String,Map<String,List<HiddenDangerTrack>>> map = new HashMap<String, Map<String,List<HiddenDangerTrack>>>();
		 for (HiddenDangerTrack hd : tracks) {
	        	Map<String,List<HiddenDangerTrack>> value = map.get(hd.getInspectionPlanName());//包含变电站名和对应的track集合
				if(value==null) {
					List<HiddenDangerTrack> lists = new ArrayList<HiddenDangerTrack>();
 					value = new  HashMap<String, List<HiddenDangerTrack>>();
					lists.add(hd);
					value.put(hd.getInspectedSubstation(), lists);
					map.put(hd.getInspectionPlanName(), value);
				}else {
					List<HiddenDangerTrack> stationOfTrack = value.get(hd.getInspectedSubstation());
					if(stationOfTrack == null) {
						stationOfTrack = new ArrayList<HiddenDangerTrack>();
						value.put(hd.getInspectedSubstation(), stationOfTrack);
					}
					stationOfTrack.add(hd);
				}
			}
		return map;
	}
	

    
	/**
	 * 根据构造的map形成treeTable
	 * @param levelTrack
	 */
	private void initTreeTable(List<HiddenDangerTrack> trackLists) {
		Map<String, Map<String, List<HiddenDangerTrack>>> trackMap = getTrackMap(trackLists);
		trackRoot = new LibTreeNode(new HiddenDangerTrackDTO(), null);
		for(Entry<String,Map<String,List<HiddenDangerTrack>>> entry:trackMap.entrySet() ) {
			Map<String,List<HiddenDangerTrack>> stationMap = entry.getValue();
			TreeNode orgRoot = new LibTreeNode("plan", new HiddenDangerTrackDTO(entry.getKey(),null), trackRoot);//把每个计划变成根节点
			for(Entry<String,List<HiddenDangerTrack>> stationEntry:stationMap.entrySet()) {
				TreeNode stationNode = new LibTreeNode("station", new HiddenDangerTrackDTO(stationEntry.getKey(),null), orgRoot);
				List<HiddenDangerTrack> tracks = stationEntry.getValue();
				for (HiddenDangerTrack track : tracks) {
					new DefaultTreeNode("track", new HiddenDangerTrackDTO(track.getId(), "--", track.getSpecificationNumber()
							, track.getVoltageLevel(), track.getIntervaName(), track.getProblemEquipment()
							, track.getInspectedMoleculeCompany(), track.getInspectedUnit()
							, track.getInspectedSubstation(), track.getHiddenDangerGrade(), track.getHiddenDangerDesc()
							, track.getCompletTimeOfRectify(), track.getRectifyPlanTime(), track.getRectifyPlanProgress()
							, track.getRectifyFinished()==1?"完成":"未完成", track.getScoreDeduction(), track.getRectificationPlan()
							, track.getElementAndRequest(), track.getCheckSubitem(), track.getExpertOfCompany()
							, track.getInspectionExpert(), track.getInspectionExpertTel(), track.getCheckInPerson()
							, track.getCheckInPersonTel(), track.getSourcesOfHiddenDanger(), track.getJurisdictionalSpecialty()
							, track.getHiddenDangerProblemClass(), track.getHiddenDangerReasonClass(), track.getScoreCriteria()
							, track.getScores(), track.getPersonOfRectify(), track.getPersonOfRectifyTel(), track.getMonthRectifyProgress()
							, track.getOpinionsOfUint(), track.getStateOfUnit(), track.getRemark()), stationNode);
				}
			}
		}
	}
	
	
    /**
     * 初始化字典Map
     */
	@SuppressWarnings("unchecked")
	private void initDics() {
		discMap = new HashMap<String, List<String>>();
		List<String> dicts = Arrays.asList("HiddenDangerQuesType","HiddenDangerReasonType","HiddenDangerLevel"	,"HiddenDangerSource");
		try {
			for (String className : dicts) {
				T=sdc.getT(className);
				List<AbstractStandardDict> dictList = (List<AbstractStandardDict>) sman.findAll(Class.forName(T.getName()));
				List<String> values = new ArrayList<String>();
				for (AbstractStandardDict d : dictList) {
					values.add(d.getName());
				}
				discMap.put(className, values);
			}
		} catch (Exception e) {
			addErrorMessage("字典库加载失败");
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 初始化自动填充列表
	 * @throws Exception 
	 */
	private void initAutoCompleteList()  {
		classList = Arrays.asList("一", "二", "三", "四", "五", "六");
		voltageList = Arrays.asList("35kV", "110kV", "220kV", "500kV", "750kV", "800kV", "1000kV");
	}
	
	/**
	 * 多重查询
	 */
	public void query() {
		try {
			tracks = trackService.findByCondition(queryParam.getCondition());
			initTreeTable(tracks);
			initTracks();
		} catch (Exception e) {
			addErrorMessage("查询失败！");
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 根据计划名称查
	 * @param query
	 * @return
	 */
	public List<String> completePlan(String query) {
		Set<String> planNames = new LinkedHashSet<String>();
		planNames.add("全部");
		for (HiddenDangerTrack  track : tracks) {
			String nameHead = PingYinUtil.getPingYinHeader(track.getInspectionPlanName());
			if (nameHead.toLowerCase().contains(query)) {
				planNames.add(track.getInspectionPlanName());
			}
			if (track.getInspectionPlanName().contains(query)) {
				planNames.add(track.getInspectionPlanName());
			}
		}
		return new ArrayList<String>(planNames);
	}
	
	/**
	 * 被检变电站集合
	 * @param query
	 * @return
	 */
	public List<String> completeStation(String query) {
		Set<String> stations = new LinkedHashSet<String>();
		stations.add("全部");
		for (HiddenDangerTrack  track : tracks) {
			String nameHead = PingYinUtil.getPingYinHeader(track.getInspectedSubstation());
			if (nameHead.toLowerCase().contains(query)) {
				stations.add(track.getInspectedSubstation());
			}
			if (track.getInspectedSubstation().contains(query)) {
				stations.add(track.getInspectedSubstation());
			}
		}
		return new ArrayList<String>(stations);
	}
	
	
	/**
	 * 专家在输入框的显示
	 * @param query
	 * @return
	 */
	public List<String> completeExpert(String query) {
		List<InspectionExpert>	selectExperts = expertService.findAll();
		Set<String> names = new HashSet<String>();
		for (InspectionExpert expert : selectExperts) {
			String nameHead = PingYinUtil.getPingYinHeader(expert.getName());
			if (nameHead.toLowerCase().contains(query)) {
				names.add(expert.getName());
			}
			if (expert.getName().contains(query)) {
				names.add(expert.getName());
			}
		}
		return new ArrayList<String>(names);
	}
	
	
	/**
	 * 电压等级
	 * @param query
	 * @return
	 */
	public List<String> completeVoltage(String query) {
		List<String> results = new ArrayList<String>();
		for (String s : voltageList) {
			if (s.contains(query)) {
				results.add(s);
			}
		}
		return results;
	}
	
	/**
	 * 问题归类
	 * @param query
	 * @return
	 * @throws Exception 
	 */
	public List<String> completeHiddenDangerQuesClass(String query) throws Exception {
		List<String> results = new ArrayList<String>();
		for (String s :  discMap.get("HiddenDangerQuesType")) {
			if (s.contains(query)) {
				results.add(s);
			}
		}
		return results;
	}
	/**
     * 原因归类
     * @param query
     * @return
	 * @throws Exception 
     */
   public List<String>  completeHiddenDangerReasonClass(String query) throws Exception {
	   List<String> results = new ArrayList<String>();
		for (String s : discMap.get("HiddenDangerReasonType")) {
			if (s.contains(query)) {
				results.add(s);
			}
		}
		return results;
   }
   /**
	 * 隐患来源
	 * @param query
	 * @return
	 */
	public List<String> completeHiddenDangerSources(String query) {
		List<String> results = new ArrayList<String>();
		for (String s : discMap.get("HiddenDangerSource")) {
			if (s.contains(query)) {
				results.add(s);
			}
		}
		return results;
	}
	 /**
	    * 管辖专业
	    * @param query
	    * @return
	    */
	public List<String>  completeHiddenDangerJSpecialty(String query) {
	    	 List<String> jSpecialtyList = new ArrayList<String>(); // 管辖专业
	    	 for (HiddenDangerTrack k_ques : tracks) {
	        	    if(!jSpecialtyList.contains(k_ques.getJurisdictionalSpecialty()) && k_ques.getJurisdictionalSpecialty()!=null) {
	        	    	jSpecialtyList.add(k_ques.getJurisdictionalSpecialty());
	    	   }
	 	}
	   return  jSpecialtyList;
	 }
	/**
	 * 对应分类
	 * @param query
	 * @return
	 */
	public List<String> completeClassify(String query) {
		List<String> results = new ArrayList<String>();
		for (String s : classList) {
			if (s.contains(query)) {
				results.add(s);
			}
		}
		return results;
	}
	
	/**
	 * 隐患等级
	 * @param query
	 * @return
	 */
	public List<String> completeHiddenGrade(String query) {
		List<String> results = new ArrayList<String>();
		for (String s :  discMap.get("HiddenDangerLevel")) {
			if (s.contains(query)) {
				results.add(s);
			}
		}
		return results;
	}
	
	/**
	 * 重置按钮调用方法
	 */
	public void resetQuery() {
		queryParam = new HiddenDangerTrackQueryParamModel();
		initTreeTable(tracks);
	}
	
	/**
	 * 删除所选
	 * @throws Exception 
	 */
	public void deleteTrack() throws Exception {
		if(selected!=null) {
			trackService.deleteById(selected.getId());
		}
		selectedNode.getParent().getChildren().remove(selectedNode);
		//initTreeTable();
		initTracks();
		addSuccessMessage("删除成功！");
		selected = null;
	}


	/**
	 * treeTable选择事件
	 * @param event
	 */
	public void onTreeTableNodeSelect(NodeSelectEvent event) {
		selectedNode = event.getTreeNode();
		if ("plan".equals(selectedNode.getType())) {
			selected = null;
	           } else if ("track".equals(selectedNode.getType())) {
	        	 String trackId = ((HiddenDangerTrackDTO) selectedNode.getData()).getTrackId();
	    	     try {
					selected = trackService.findById(trackId);
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
	}
	public void onNodeUnSelect(NodeUnselectEvent event) {
	}
	
	public void onDialogReturn() {
//		initTracks();
//		initTreeTable(tracks);
		PrimeFaces.current().ajax().update(Arrays.asList(":form:dataTb"));
	}
	/**
	 * 改变编辑和查看详细的显示状态
	 */
	public void preEdit() {
		changeStatus= "true";
		status = true;
		
	}
	public void changeStatus() {
		status = false;
		changeStatus= "false";
	}
	public List<HiddenDangerTrack> getTracks() {
		return tracks;
	}
	public void setTracks(List<HiddenDangerTrack> tracks) {
		this.tracks = tracks;
	}
	public HiddenDangerTrack getSelected() {
		return selected;
	}
	public void setSelected(HiddenDangerTrack selected) {
		this.selected = selected;
	}
	public boolean isStatus() {
		return status;
	}
	public void setStatus(boolean status) {
		this.status = status;
	}
	public TreeNode getSelectedNode() {
		return selectedNode;
	}

	public void setSelectedNode(TreeNode selectNode) {
		this.selectedNode = selectNode;
	}

	public TreeNode getTrackRoot() {
		return trackRoot;
	}

	public void setTrackRoot(TreeNode trackRoot) {
		this.trackRoot = trackRoot;
	}
	public HiddenDangerTrackQueryParamModel getQueryParam() {
		return queryParam;
	}
	public void setQueryParam(HiddenDangerTrackQueryParamModel queryParam) {
		this.queryParam = queryParam;
	}

	public String getChangeStatus() {
		return changeStatus;
	}

	public void setChangeStatus(String changeStatus) {
		this.changeStatus = changeStatus;
	}



}
